package com.runvp.service.biz.service.impl;

import com.runvp.common.core.text.Convert;
import com.runvp.common.enums.EnableStatus;
import com.runvp.common.exception.base.BaseException;
import com.runvp.common.util.OrderNoUtils;
import com.runvp.common.util.ToolUtils;
import com.runvp.common.util.auth.SecurityUtils;
import com.runvp.common.utils.DateUtils;
import com.runvp.common.utils.validtion.CheckException;
import com.runvp.service.biz.domain.BizCustomer;
import com.runvp.service.biz.domain.BizCustomerEquity;
import com.runvp.service.biz.handler.ClientOutHandler;
import com.runvp.service.biz.mapper.BizCustomerEquityMapper;
import com.runvp.service.biz.mapper.BizCustomerMapper;
import com.runvp.service.biz.service.IBizCustomerEquityService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 顾客权益Service业务层处理
 * 
 * @author runvp
 * @date 2022-12-31
 */
@Slf4j
@Service
public class BizCustomerEquityServiceImpl implements IBizCustomerEquityService {
    @Autowired
    private BizCustomerEquityMapper bizCustomerEquityMapper;
    @Autowired
    private BizCustomerMapper bizCustomerMapper;
    @Autowired
    private ClientOutHandler clientOutHandler;


    /**
     * 权益核销
     * @param code
     * @param phone
     * @return boolean
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean consumption(String sn,String code,String phone){
        if(StringUtils.isBlank(sn)){
            throw new BaseException("设备号为空");
        }
        if(StringUtils.isBlank(code) && StringUtils.isBlank(phone)){
            throw new BaseException("核销凭证为空");
        }
        String type = "";
        Long uid = SecurityUtils.getUserId();
        BizCustomerEquity equity;
        if(StringUtils.isNotBlank(code)){
            type = "核销码【"+code+"】";
            equity = getBizCustomerEquityByCode(code);
        }else {
            type = "手机号【"+phone+"】";
            equity = getBizCustomerEquityByPhone(phone);
        }
        CheckException.emptyThrowException(equity,"权益不存在或已核销");
        if(!sn.equals(equity.getSn())){
            throw new BaseException("本设备未找到您的权益");
        }
        int stock = ToolUtils.toInt(equity.getStock());
        //校验库存是否足够
        if(stock <= 0){
            throw new BaseException("您的权益已核销完毕");
        }
        //执行充电
        boolean r = clientOutHandler.out(equity.getSn(),equity.getCargo(),SecurityUtils.getStrUserId());
        if(r){
            //扣除库存
            equity.setStock(stock-1);
            equity.setRemark(ToolUtils.toStr(equity.getRemark())+"渠道用户【"+uid+"】"+DateUtils.now()+" 通过"+type+"完成一次核销\n");
            updateBizCustomerEquity(equity);
        }
        return true;
    }
    /**
     * 查询顾客权益
     * 
     * @param id 顾客权益主键
     * @return 顾客权益
     */
    @Override
    public BizCustomerEquity selectBizCustomerEquityById(Long id) {
        return bizCustomerEquityMapper.selectBizCustomerEquityById(id);
    }

    /**
     * 查询顾客权益列表
     * 
     * @param bizCustomerEquity 顾客权益
     * @return 顾客权益
     */
    @Override
    public List<BizCustomerEquity> selectBizCustomerEquityList(BizCustomerEquity bizCustomerEquity) {
        return bizCustomerEquityMapper.selectBizCustomerEquityList(bizCustomerEquity);
    }
    /**
     * 生成充电码
     * @return str
     */
    @Override
    public String createCode(){
        String code;
        BizCustomerEquity old;
        for (int i = 0; i < 10; i++) {
            code = OrderNoUtils.verifyCode();
            old = getBizCustomerEquityByCode(code);
            log.info("第【{}】次生成充电码:{}",(i+1),code);
            if(old == null){
                return code;
            }
        }
        throw new BaseException("生成失败,请重试");
    }

    /**
     * 根据充电码查询对象
     * @param code
     * @return BizCustomerEquity
     */
    private BizCustomerEquity getBizCustomerEquityByCode(String code){
        BizCustomerEquity query = new BizCustomerEquity();
        query.setCode(code);
        query.setStatus(EnableStatus.ENABLE.getCode());
        List<BizCustomerEquity> equities = selectBizCustomerEquityList(query);
        if(CollectionUtils.isEmpty(equities)){
            return null;
        }
        return equities.get(0);
    }
    /**
     * 根据phone查询对象
     * @param phone
     * @return BizCustomerEquity
     */
    private BizCustomerEquity getBizCustomerEquityByPhone(String phone){
        BizCustomerEquity query = new BizCustomerEquity();
        query.setPhone(phone);
        query.setStatus(EnableStatus.ENABLE.getCode());
        List<BizCustomerEquity> equities = selectBizCustomerEquityList(query);
        if(CollectionUtils.isEmpty(equities)){
            return null;
        }
        return equities.get(0);
    }
    /**
     * 新增顾客权益
     * 
     * @param bizCustomerEquity 顾客权益
     * @return 结果
     */
    @Override
    public int insertBizCustomerEquity(BizCustomerEquity bizCustomerEquity) {
        check(bizCustomerEquity);
        BizCustomerEquity old = getBizCustomerEquityByPhone(bizCustomerEquity.getPhone());
        if(null != old){
            throw new BaseException("该手机号存在未核销的权益");
        }
        BizCustomer query = new BizCustomer();
        query.setPhone(bizCustomerEquity.getPhone());
        List<BizCustomer> customer = bizCustomerMapper.selectBizCustomerList(query);
        if(!CollectionUtils.isEmpty(customer)){
            bizCustomerEquity.setCustomerId(customer.get(0).getId());
        }
        bizCustomerEquity.setCreateTime(DateUtils.getNowDate());
        return bizCustomerEquityMapper.insertBizCustomerEquity(bizCustomerEquity);
    }

    /**
     * 校验普通规则
     * @param bizCustomerEquity
     */
    private void check(BizCustomerEquity bizCustomerEquity){
        if(ToolUtils.toInt(bizCustomerEquity.getStock()) > ToolUtils.toInt(bizCustomerEquity.getEquity())){
            throw new BaseException("库存不能大于权益数");
        }
    }
    /**
     * 修改顾客权益
     * 
     * @param bizCustomerEquity 顾客权益
     * @return 结果
     */
    @Override
    public int updateBizCustomerEquity(BizCustomerEquity bizCustomerEquity) {
        check(bizCustomerEquity);
        bizCustomerEquity.setUpdateTime(DateUtils.getNowDate());
        return bizCustomerEquityMapper.updateBizCustomerEquity(bizCustomerEquity);
    }

    /**
     * 批量删除顾客权益
     * 
     * @param ids 需要删除的顾客权益主键
     * @return 结果
     */
    @Override
    public int deleteBizCustomerEquityByIds(String ids) {
        return bizCustomerEquityMapper.deleteBizCustomerEquityByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除顾客权益信息
     * 
     * @param id 顾客权益主键
     * @return 结果
     */
    @Override
    public int deleteBizCustomerEquityById(Long id) {
        return bizCustomerEquityMapper.deleteBizCustomerEquityById(id);
    }
}
